// document.writeln("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>");
// document.writeln("<script type='text/javascript' src='https://rawgit.com/schmich/instascan-builds/master/instascan.min.js'></script>");
// document.writeln("<script type='text/javascript' src='/static/cews_static/vendor/instascan/instascan.min.js'></script>");
class GnsScan {

    constructor(on_scan,title="Scan QRCode") {
        this._id = this.makeid(8)
        this.is_play = false
        this.check_button = false
        this.check_button_text = false
        this.username_span = false
        this.is_render = false
        this.on_scan = on_scan
        this.title = title
        // canvas 
        this.canvas =  false
        this.video =  false
        this.ctx = false

        // scan
        this.scanner = false
        this.render()
        this.register()
    }

    makeid(length) {
        var result = '';
        var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for (var i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() *
                charactersLength));
        }
        return result;
    }

    render() {
        let html = `
        <div class="modal fade" id="${this._id}scan_modal" tabindex="-1" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${this.title}</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                    </div>
                    <div id="${this._id}scan_modal__alert">

                    </div>
                    
                    <video id="${this._id}preview" class="d-none">
                        
                    </video>
                    <canvas id="${this._id}preview__canvas">
                    </canvas>
        
                </div>
            </div>
        </div>
        `
        $('body').append(html)
        this.is_render = true
    }

    setAlert(content) {
        let html = `
        <div id="${this._id}scan_modal__alert" class="alert alert-warning mb-0 alert-dismissible fade show" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        <strong id="${this._id}scan_modal__alert__content">${content}</strong> 
        </div>
        `
        $('#'+this._id + 'scan_modal__alert').html(html)
    }

    drawCanvas(that) {
        let canvas = that.canvas
        let ctx = that.ctx
        let video = that.video
        let is_play = that.is_play
        
        console.log(that.is_play)
        if (!is_play)
            return
        

        canvas.height = video.videoHeight
        canvas.width = video.videoWidth

        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

        var faceArea = 300;
        var pX = canvas.width / 2 - faceArea / 2;
        var pY = canvas.height / 2 - faceArea / 2;

        ctx.rect(pX, pY, faceArea, faceArea);
        ctx.lineWidth = "3";
        ctx.strokeStyle = "cyan";
        ctx.stroke();

        setTimeout(function(){
            that.drawCanvas(that)
        }, 1000 / 30)
    }

    register() {
        this.check_button = $('#'+this._id + 'final_check_as_other')
        this.check_button_text = $('#'+this._id + 'checkbutton-text')
        this.username_span = $('#'+this._id + 'scaned_username')

        this.canvas = document.getElementById(this._id + 'preview__canvas')
        this.video = document.getElementById(this._id + 'preview')
        this.ctx = this.canvas.getContext("2d")

        // console.log(id_stockcode, search_btn);
        
        let that = this
        this.scanner = new Instascan.Scanner({ video: document.getElementById(this._id+'preview'), mirror: false, });
        this.scanner.addListener('scan', function (content) {
            // alert(content);
            if (that.on_scan){
                that.on_scan(content)
            }
            // data = that.getCheckUser(content)
            //     .then(response => {
            //         data = response.data
            //         that.on_result(response)
            //         if (!data.ack) {
            //             that.setAlert(data.err)
            //             return
            //         }
            //         // setUI(data.username)
            //         // setUser_id(data.user_id)

            //     })
        });
      
        // $('#'+this._id + 'preview').on('play', function () {
        //     that.is_play = true
        //     console.log('on preview play')
        //     setTimeout(function(){
        //         that.drawCanvas(that)
        //     }, 300)
        // })

        $('#'+this._id + 'preview').on('stop', _ => {
            
            that.is_play = false
            console.log("on pre view stop")
        })

        $('#'+this._id + 'scan_modal').on('hide.bs.modal', function () {
            try {
                that.is_play = false
                $('#'+that._id + 'scan_modal__alert').html('')
            
                that.scanner.stop()
                console.log('scanner stop')
            } catch {
                console.log("Erron while stopping scanner.")
            }
        })

    }
    instascan = function () {
        let that = this
        
        $('#'+this._id + 'scan_modal').modal('show')
        // draw focus area on canvas
        Instascan.Camera.getCameras().then(function (cameras) {
            if (cameras.length > 0) {
                that.is_play = true
                console.log('scanner start')
                that.scanner.start(cameras[cameras.length - 1]);
                setTimeout(function(){that.drawCanvas(that)},1000/30)
            } else {
                that.setAlert('No cameras found.');
            }
        }).catch(function (e) {
            console.error(e);
            that.setAlert('No cameras found.')
        });
    }
    close(){
        this.is_play = false
        $('#'+this._id + 'scan_modal').modal('hide')
    }
}